{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "clear-microwave",
   "metadata": {},
   "outputs": [],
   "source": [
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "from argparse import Namespace\n",
    "import json\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "first-eight",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scripts.train import DataModule, _to_image, KeypointModule"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "monthly-prince",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('../config/cups.json', 'rt') as f:\n",
    "    keypoint_config = json.load(f)\n",
    "module = DataModule(Namespace(train='/home/ken/data/cups_train/', val='/home/ken/data/cups_test/', batch_size=1, workers=1, pool=32), keypoint_config=keypoint_config)\n",
    "module.setup('fit')\n",
    "\n",
    "dataloader = module.val_dataloader()\n",
    "print(dataloader)\n",
    "train_iterator = iter(dataloader)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "considered-parish",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "def resize(target, width=320, height=180):\n",
    "    return cv2.resize(target, (width, height))\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "composed-charleston",
   "metadata": {},
   "outputs": [],
   "source": [
    "module = KeypointModule.load_from_checkpoint('../lightning_logs/version_0/checkpoints/epoch=15-step=33567.ckpt', keypoint_config=keypoint_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "mineral-vacuum",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = module.model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "available-cancellation",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "frame, target, depth, centers = next(train_iterator)\n",
    "\n",
    "plt.figure(figsize=(14, 8))\n",
    "image = _to_image(frame[0].numpy())\n",
    "for i in range(2):\n",
    "    for j in range(2):\n",
    "        axis = plt.subplot2grid((2, 2), loc=(i, j))\n",
    "        axis.imshow(resize(image))\n",
    "        axis.imshow(resize(target[0, i * 2 + j].numpy()), alpha=0.7)\n",
    "        plt.axis('off')\n",
    "plt.tight_layout()\n",
    "pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "crazy-bookmark",
   "metadata": {},
   "outputs": [],
   "source": [
    "with torch.no_grad():\n",
    "    heatmap_p, depth_p, centers_p = model(frame)\n",
    "    heatmap_p = torch.sigmoid(heatmap_p)\n",
    "\n",
    "plt.figure(figsize=(14, 8))\n",
    "image = _to_image(frame[0].numpy())\n",
    "for i in range(2):\n",
    "    for j in range(2):\n",
    "        axis = plt.subplot2grid((2, 2), loc=(i, j))\n",
    "        axis.imshow(resize(image))\n",
    "        axis.imshow(resize(heatmap_p[0, i * 2 + j].detach().numpy()), alpha=0.7, vmin=0.0, vmax=1.0)\n",
    "        plt.axis('off')\n",
    "plt.tight_layout()\n",
    "pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "742832fc-bb90-4de5-8360-1af36bb7f8d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "with torch.no_grad():\n",
    "    heatmap_p, depth_p, centers_p = model(frame)\n",
    "\n",
    "plt.figure(figsize=(14, 8))\n",
    "image = _to_image(frame[0].numpy())\n",
    "plt.imshow(resize(depth_p[0, 3].detach().numpy()), alpha=0.7, vmin=0.0, vmax=2.0)\n",
    "plt.axis('off')\n",
    "plt.tight_layout()\n",
    "pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "sacred-cotton",
   "metadata": {},
   "outputs": [],
   "source": [
    "pixel_indices = np.zeros((2, 180, 320), dtype=np.float32)\n",
    "for i in range(180):\n",
    "    for j in range(320):\n",
    "        pixel_indices[:, i, j] = [j + 0.5, i + 0.5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "indonesian-steam",
   "metadata": {},
   "outputs": [],
   "source": [
    "vectors = centers.numpy()[0]\n",
    "norms = np.linalg.norm(vectors, axis=0)\n",
    "where_non_zero = np.abs(norms) > 1e-1\n",
    "gt_centers = np.zeros((2, pixel_indices.shape[1], pixel_indices.shape[2]), dtype=np.float32)\n",
    "gt_centers[:, where_non_zero] = pixel_indices[:, where_non_zero] + vectors[:, where_non_zero]\n",
    "\n",
    "where_heatmap_non_zero = heatmap_p[0].numpy().sum(axis=0) > 0.1\n",
    "p_centers = np.zeros((2, pixel_indices.shape[1], pixel_indices.shape[2]), dtype=np.float32)\n",
    "p_centers[:, where_heatmap_non_zero] = pixel_indices[:, where_heatmap_non_zero] + centers_p[0].detach().numpy()[:, where_heatmap_non_zero]\n",
    "\n",
    "figure = plt.figure(figsize=(10, 5))\n",
    "dotted_image = cv2.resize(image.copy(), (320, 180))\n",
    "for point in gt_centers[:, where_non_zero].transpose():    \n",
    "    cv2.circle(dotted_image, (point[0], point[1]), 2, (255, 0, 0), -1)\n",
    "    \n",
    "dotted_image_pred = cv2.resize(image.copy(), (320, 180))\n",
    "for point in p_centers[:, where_non_zero].transpose():    \n",
    "    cv2.circle(dotted_image_pred, (point[0], point[1]), 2, (255, 0, 0), -1)\n",
    "\n",
    "axis = plt.subplot2grid((1, 2), loc=(0, 0))\n",
    "axis.imshow(dotted_image)\n",
    "plt.axis('off')\n",
    "\n",
    "axis = plt.subplot2grid((1, 2), loc=(0, 1))\n",
    "axis.imshow(dotted_image_pred)\n",
    "plt.axis('off')\n",
    "pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hindu-tuesday",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "essential-receiver",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "marine-alliance",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "vision",
   "language": "python",
   "name": "vision"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
